package com.aids_malaria.ui.datacollect;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.MosquitoInvest;
import com.aids_malaria.util.DisplayUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.ConfirmDialog;
import com.aids_malaria.widget.titlebar.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MosquitoBorneDataEditActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.tv_mosquito_sort_name)
    TextView tv_mosquito_sort_name;
    @BindView(R.id.et_density)
    EditText et_density;
    @BindView(R.id.et_biting_rate)
    EditText et_biting_rate;
    @BindView(R.id.et_positive_infection_rate)
    EditText et_positive_infection_rate;

    public static final String KEY_MOSQUITO_INVEST = "mosquito_invest";
    public static final String KEY_IS_CREATE = "is_create";

    private MosquitoInvest mMosquitoInvest;
    private boolean isCreate;

    private String preDensity = "";
    private String preBiting_rate = "";
    private String prePositive_infection_rate = "";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_mosquito_borne_data_edit;
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        if(null != bundle){
            mMosquitoInvest = (MosquitoInvest) bundle.getSerializable(KEY_MOSQUITO_INVEST);
            isCreate = bundle.getBoolean(KEY_IS_CREATE);
            tv_mosquito_sort_name.setText(mMosquitoInvest.getSortTypeName());

            if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_AEDES){
                et_density.setText("" + mMosquitoInvest.getAedes_density());
                et_biting_rate.setText("" + mMosquitoInvest.getAedes_bit_rate());
                et_positive_infection_rate.setText("" + mMosquitoInvest.getAedes_infect_rate());
            }else if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_ANOPHELES){
                et_density.setText("" + mMosquitoInvest.getAnopheles_density());
                et_biting_rate.setText("" + mMosquitoInvest.getAnopheles_bit_rate());
                et_positive_infection_rate.setText("" + mMosquitoInvest.getAnopheles_infect_rate());
            }else if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_CULEX){
                et_density.setText("" + mMosquitoInvest.getCulex_density());
                et_biting_rate.setText("" + mMosquitoInvest.getCulex_bit_rate());
                et_positive_infection_rate.setText("" + mMosquitoInvest.getCulex_infect_rate());
            }else{
                et_density.setText("" + mMosquitoInvest.getOther_density());
                et_biting_rate.setText("" + mMosquitoInvest.getOther_bit_rate());
                et_positive_infection_rate.setText("" + mMosquitoInvest.getOther_infect_rate());
            }

            preDensity = et_density.getText().toString().trim();
            preBiting_rate = et_biting_rate.getText().toString().trim();
            prePositive_infection_rate = et_positive_infection_rate.getText().toString().trim();
        }
        initTitleBar(title_bar,getString(R.string.mosquito_borne_data_edit));
    }

    @Override
    public void back() {
        if (preDensity.equals(et_density.getText().toString().trim()) && preBiting_rate.equals(et_biting_rate.getText().toString().trim())
        && prePositive_infection_rate.equals(et_positive_infection_rate.getText().toString().trim())){
            finish();
            return;
        }

        String tipString = isCreate ? getString(R.string.tip_data_add):getString(R.string.tip_data_modify);
        ConfirmDialog.newInstance(true, getString(R.string.hint), tipString)
                .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void confirm() {
                        finish();
                    }
                })
                .setOutCancel(true)
                .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                .show(getSupportFragmentManager());

    }

    @OnClick({R.id.tv_confirm})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_confirm:
                String bitingRate = et_biting_rate.getText().toString().trim();
                String density = et_density.getText().toString().trim();
                String positiveInfectionRate = et_positive_infection_rate.getText().toString().trim();
                if(StringUtil.isEmpty(bitingRate) || StringUtil.isEmpty(density) || StringUtil.isEmpty(positiveInfectionRate)){
                    ToastUtil.showToast(ResourceUtil.getString(R.string.input_can_not_be_empty));
                    return;
                }
                Boolean isEdit = false;
                if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_AEDES){
                    isEdit = (mMosquitoInvest.getAedes_bit_rate() != Double.valueOf(bitingRate)
                    || mMosquitoInvest.getAedes_density() != Double.valueOf(density)
                    || mMosquitoInvest.getAedes_infect_rate() != Double.valueOf(positiveInfectionRate));
                    mMosquitoInvest.setAedes_bit_rate(Double.valueOf(bitingRate));
                    mMosquitoInvest.setAedes_density(Double.valueOf(density));
                    mMosquitoInvest.setAedes_infect_rate(Double.valueOf(positiveInfectionRate));
                }else if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_ANOPHELES){
                    isEdit = (mMosquitoInvest.getAnopheles_bit_rate() != Double.valueOf(bitingRate)
                            || mMosquitoInvest.getAnopheles_density() != Double.valueOf(density)
                            || mMosquitoInvest.getAnopheles_infect_rate() != Double.valueOf(positiveInfectionRate));
                    mMosquitoInvest.setAnopheles_bit_rate(Double.valueOf(bitingRate));
                    mMosquitoInvest.setAnopheles_density(Double.valueOf(density));
                    mMosquitoInvest.setAnopheles_infect_rate(Double.valueOf(positiveInfectionRate));
                }else if(mMosquitoInvest.getSortType() == MosquitoInvest.SORT_TYPE_CULEX){
                    isEdit = (mMosquitoInvest.getCulex_bit_rate() != Double.valueOf(bitingRate)
                            || mMosquitoInvest.getCulex_density() != Double.valueOf(density)
                            || mMosquitoInvest.getCulex_infect_rate() != Double.valueOf(positiveInfectionRate));
                    mMosquitoInvest.setCulex_bit_rate(Double.valueOf(bitingRate));
                    mMosquitoInvest.setCulex_density(Double.valueOf(density));
                    mMosquitoInvest.setCulex_infect_rate(Double.valueOf(positiveInfectionRate));
                }else{
                    isEdit = (mMosquitoInvest.getOther_bit_rate() != Double.valueOf(bitingRate)
                            || mMosquitoInvest.getOther_density() != Double.valueOf(density)
                            || mMosquitoInvest.getOther_infect_rate() != Double.valueOf(positiveInfectionRate));
                    mMosquitoInvest.setOther_bit_rate(Double.valueOf(bitingRate));
                    mMosquitoInvest.setOther_density(Double.valueOf(density));
                    mMosquitoInvest.setOther_infect_rate(Double.valueOf(positiveInfectionRate));
                }
                if(isOnLine()){
                    String dataJson = GsonUtil.beanToJson(mMosquitoInvest);
                    LogUtil.d("dataJson:------------" + dataJson);
                    saveMosquitoInvest(isCreate?"1":"2", dataJson);
                }else{
                    //修改本地
                    mMosquitoInvest.setBusy_type(isCreate?"1":"2");
                    if(isCreate){
                        mMosquitoInvest.setCreateOrUpdate(true);
//                        LiteOrmUtil.getLiteOrm().insert(mMosquitoInvest);
                        DBManager.get().mosquitoInvestDao().insert(mMosquitoInvest);
                    }else{
                        mMosquitoInvest.setCreateOrUpdate(isEdit);
                        DBManager.get().mosquitoInvestDao().update(mMosquitoInvest);
                    }
                    ToastUtil.showToast(ResourceUtil.getString(R.string.operate_success));
                    setResult(200);
                    finish();
                }

                break;
        }
    }

    /**
     * 保存蚊媒数据
     * @param busy_type  保存类型 1插入 2更改 3 删除
     * @param data
     * @return
     */
    private void saveMosquitoInvest(String busy_type, String data) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).saveMosquitoInvest(busy_type, requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(getString(R.string.operate_success));
                        setResult(200);
                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

}
